import React, { Component ,ChangeEvent} from 'react'
import { connect } from 'react-redux'
import {InitState} from '../types/index'
import {RouteComponentProps} from 'react-router-dom'
import '../css/index.scss'
interface Props extends InitState,RouteComponentProps {

}
interface State {
    
}

export class Login extends Component<Props, State> {
    setTime:any
    state = {

        name:'',
        pwd:''
    }

    changeUp=(e:ChangeEvent)=>{
        this.setState({
            [(e.target as HTMLInputElement).name]:(e.target as HTMLInputElement).value
        })
    }
    // 9、登录、注册实现防抖操作
    login=()=>{
        const {name,pwd } = this.state
        if(!name||!pwd){
            alert('格式错误')
        }
        if(name==='123'&&pwd==='123'){
            alert('登陆成功')
            // 10、实现登录态数据持久化、防抖功能
            sessionStorage.setItem('token',name)
            this.props.history.replace('/')
        }else{
            alert('账号或密码错误，要不你在试试？')
        }
    }
    //防抖
    fangdou=(callback:Function,time:number=1000)=>{
        clearTimeout(this.setTime)
        this.setTime= setTimeout(() => {
            callback()
        }, time);
    }
    render() {
        const {name,pwd} = this.state
        return (
            // 8、自行设计完成登录、注册开发(不要求排版)
            <div className='login'>

                <p>账号：<input type="text" name='name' value={name} onChange={this.changeUp}/></p>
                <br />
                <br /><br />
                <p>密码：<input type="text" name='pwd' value={pwd} onChange={this.changeUp}/></p>
                <br />
                <br />
                <br />
                <button onClick={()=>this.fangdou(this.login)}>登录</button>
            </div>
        )
    }
}

const mapStateToProps = (state:Props) => ({
    list:state.list,
    ind:state.ind
})

const mapDispatchToProps = (dispatch:Function)=>({
})

export default connect(mapStateToProps, mapDispatchToProps)(Login)
